package com.weixin.utils;

/**
 * 
  * @ClassName: WxBase32
  * @Description: Base32加解密
  * @author 马正正
  * @date 2016年1月22日
 */
public class WxBase32 {
	private static final char[] ENCODE={
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',  
        'Y', 'Z', '2', '3', '4', '5', '6', '7'
	};
	
	private static final byte[] DECODE=new byte[128];
	static{
		for(int i=0;i<DECODE.length;i++){
			DECODE[i]=(byte)0xFF;
		}
		for(int i=0;i<ENCODE.length;i++){
			DECODE[ENCODE[i]]=(byte)i;
		}
	}
	
	public static String encode(byte[] data){
		char[] chars = new char[((data.length * 8) / 5) + ((data.length % 5) != 0 ? 1 : 0)];  
        
        for (int i = 0, j = 0, index = 0; i < chars.length; i++) {  
            if(index > 3){
                int b = data[j] & (0xFF >> index);  
                index = (index + 5) % 8;  
                b <<= index;  
                if (j < data.length - 1) {  
                    b |= data[j + 1] >> (8 - index);  
                }  
                chars[i] = ENCODE[b];  
                j++;  
            }else{  
                chars[i] = ENCODE[((data[j] >> (8 - (index + 5))) & 0x1F)];  
                index = (index + 5) % 8;  
                if (index == 0) {  
                    j++;  
                }  
            }  
        }  
          
        return new String(chars);  
	}
	
	public static byte[] decode(String s) {  
        
        char[] stringData = s.toCharArray();  
        byte[] data = new byte[(stringData.length * 5) / 8];  
          
        for (int i = 0, j = 0, index = 0; i < stringData.length; i++) {  
        	int val = DECODE[stringData[i]];  
            if (val == 0xFF) {  
                throw new RuntimeException("Illegal character");  
            }  
              
            if (index <= 3) {  
                index = (index + 5) % 8;  
                if (index == 0) {  
                    data[j++] |= val;  
                }else {  
                    data[j] |= val << (8 - index);  
                }  
            } else {  
                index = (index + 5) % 8;  
                data[j++] |= (val >> index);  
                if (j < data.length) {  
                    data[j] |= val << (8 - index);  
                }  
            }  
        }  
          
        return data;  
    } 
	
	public static void main(String[] args) throws Exception{
		String str="http://xiaxingwork.iteye.com/blog/1728140";
		System.out.println(str);
		String s=encode(str.getBytes());
		System.out.println(s);
		System.out.println(new String(decode("999")));
	}
}
